<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>任务配置记录列表</div>
        <div class="flex">
          <el-button
            type="primary"
            v-if="config_list.length"
            @click="get_node_list()"
            >任务子任务配置</el-button
          >
          <el-button type="primary" @click="show_config_box = true"
            >新增</el-button
          >
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="config_list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="配置编号"
          prop="code"
          key="配置编号"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="启用时间"
          key="启用时间"
          sortable
          v-if="header_list[1].showTable"
          ><template #default="scope">
            <div v-if="scope.row.enableTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.enableTime), 'YYYY-MM-DD') }}
            </div>
            <div v-else>-- --</div>
          </template></el-table-column
        >
        <el-table-column
          label="结束时间"
          key="结束时间"
          sortable
          v-if="header_list[2].showTable"
          ><template #default="scope">
            <div v-if="scope.row.endTime ?? '' !== ''">
              {{ formatDate(parseInt(scope.row.endTime), 'YYYY-MM-DD') }}
            </div>
            <div v-else>不限</div>
          </template></el-table-column
        >
        <el-table-column
          label="备注"
          key="备注"
          sortable
          prop="remark"
          show-overflow-tooltip
          v-if="header_list[3].showTable"
        ></el-table-column>
        <el-table-column label="操作">
          <template #default="scope: any">
            <el-button @click="item_info(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="list_debounce()"
        @current-change="list_debounce()"
      />
    </div>
  </div>
  <el-drawer
    v-model="show_config_box"
    direction="rtl"
    size="60%"
    destroy-on-close
    @close="resetConfigForm(addConfigForm)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_config_form_data.id == ''">新增配置</h4>
      <h4 v-else>查看配置</h4>
    </template>
    <template #default>
      <el-form
        ref="addConfigForm"
        :model="add_config_form_data"
        :rules="task_rules"
        label-width="100px"
      >
        <el-form-item label="配置编号" prop="code">
          <el-input
            :disabled="add_config_form_data.id != ''"
            v-model="add_config_form_data.code"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="启用时间" prop="enableTime">
          <el-date-picker
            :disabled="add_config_form_data.id != ''"
            v-model="add_config_form_data.enableTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
            placeholder="请选择"
            @change="
              () => {
                add_config_form_data.endTime =
                  add_config_form_data.enableTime > add_config_form_data.endTime
                    ? ''
                    : add_config_form_data.endTime
              }
            "
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="add_config_form_data.endTime"
            type="date"
            format="YYYY-MM-DD"
            value-format="x"
            placeholder="请选择"
            :disabled="
              add_config_form_data.enableTime == '' ||
              add_config_form_data.id != ''
            "
            :disabled-date="disabledEnable"
          />
        </el-form-item>
        <el-form-item label="任务列表">
          <el-table
            :data="add_config_form_data.id == '' ? list : detailList"
            border
            class="tc"
            max-height="500px"
          >
            <el-table-column label="任务名称" prop="name"> </el-table-column>
            <el-table-column label="任务编码" prop="code"></el-table-column>
            <el-table-column
              label="当前任务权重"
              prop="current_weight"
            ></el-table-column>
            <el-table-column label="任务权重">
              <template #default="scope">
                <el-input-number
                  :max="100"
                  :min="0"
                  v-model="scope.row.weight"
                  :disabled="
                    !scope.row.isEnable || add_config_form_data.id != ''
                  "
                  placeholder="请输入"
                ></el-input-number>
              </template> </el-table-column
            ><el-table-column label="操作" v-if="add_config_form_data.id == ''">
              <template #default="scope">
                <el-button @click="edit_list({ item: scope.row, type: 1 })"
                  >编辑</el-button
                >
                <el-button
                  @click="edit_list({ item: scope.row, type: 2 })"
                  v-if="scope.row.isEnable"
                  >禁用</el-button
                >
                <el-button
                  @click="edit_list({ item: scope.row, type: 3 })"
                  v-else
                  >启用</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button
            v-if="add_config_form_data.id == ''"
            class="m_top10"
            type="primary"
            @click="show_box = true"
            >新增任务</el-button
          >
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            :disabled="add_config_form_data.id != ''"
            type="textarea"
            v-model="add_config_form_data.remark"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetConfigForm(addConfigForm)">取消</el-button>
          <el-button
            @click="submit_config(addConfigForm)"
            type="primary"
            v-if="add_config_form_data.id == ''"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="30%"
    destroy-on-close
    @close="resetForm(addTaskform)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">
        新增任务<span v-if="show_node_box">子任务</span>
      </h4>
      <h4 v-else>编辑任务<span v-if="show_node_box">子任务</span></h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="addTaskform"
        :rules="task_rules"
        label-width="140px"
      >
        <el-form-item
          :label="show_node_box ? '任务子任务名称' : '任务名称'"
          prop="name"
        >
          <el-input
            v-model="add_form_data.name"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="任务编码" prop="code" v-if="!show_node_box">
          <el-input
            v-model="add_form_data.code"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort" v-else>
          <el-input
            v-model="add_form_data.sort"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetForm(addTaskform)">取消</el-button>
          <el-button type="primary" @click="submit_task(addTaskform)"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <el-drawer
    v-model="show_node_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <template #title>
      <h4>任务子任务</h4>
    </template>
    <template #default>
      <el-button @click="show_box = true" type="primary">新增子任务</el-button>
      <el-table :data="node_list" border class="tc m_top10" max-height="800">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column label="状态" prop="name">
          <template #default="scope">
            <div v-if="scope.row.isEnable">启用</div>
            <div v-else>禁用</div>
          </template></el-table-column
        >
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="edit_node_list({ item: scope.row, type: 1 })"
              >编辑</el-button
            >
            <el-button
              v-if="!scope.row.isEnable"
              @click="edit_node_list({ item: scope.row, type: 2 })"
              >启用</el-button
            >
            <el-button
              v-else
              @click="edit_node_list({ item: scope.row, type: 2 })"
              >禁用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  check_role,
  debounce,
  formatDate,
  handle_search_key,
} from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus'
const addTaskform = ref<FormInstance>()
const addConfigForm = ref<FormInstance>()
const show_box = ref(false)
const show_config_box = ref(false)
const show_node_box = ref()
const disabledEnable = (time) => {
  return time.getTime() < add_config_form_data.value.enableTime
}
const task_rules = ref({
  // 表单验证规则
  name: [
    {
      required: true,
      message: show_box.value ? '请输入任务名称' : '请输入子任务名称',
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: show_box.value ? '请输入任务编码' : '请输入配置编号',
      trigger: 'blur',
    },
  ],
  weight: [{ required: true, message: '请输入任务权重', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  assignWeight: [
    { required: true, message: '请输入分配权重', trigger: 'blur' },
  ],
  enableTime: [
    { required: true, message: '请选择启用日期', trigger: 'change' },
  ],
})
const list = ref([])
const node_list = ref([])
const max_height = ref()
const loading = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '配置编号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '启用时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: true,
    options: [],
  },
  {
    label: '结束时间',
    value: '',
    showTable: true,
    type: 'date',
    isShow: false,
    options: [],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 10,
  enableTime: '',
  endTine: '',
  remark: '',
  code: '',
})
const add_form_data = ref({
  id: '',
  name: '',
  code: '',
  assignWeight: '',
  weight: '',
  sort: '',
})
const add_config_form_data = ref({
  id: '',
  code: '',
  detailList: [],
  enableTime: '',
  endTime: '',
  remark: '',
})
const submit_config = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      let all_weight = 0
      list.value.forEach((i) => {
        all_weight += Number(i.weight)
      })
      if (all_weight != 100) {
        ElMessage.error('任务权重之和必须为100')
        return
      }
      ElMessageBox.confirm('新增后不可更改，如需更改需再次新增', '', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false,
        type: 'warning',
      })
        .then(() => {
          let data = []
          list.value.forEach((i) => {
            if (i.isEnable) {
              let obj = { taskConfigId: i.id, weight: i.weight }
              data.push(obj)
            }
          })
          add_config_form_data.value.detailList = data
          axios
            .request({
              url: serviceApi.taskWeightConfig,
              method: 'post',
              data: add_config_form_data.value,
            })
            .then((res) => {
              console.log(res)
              ElMessage.success('操作成功！')
              setTimeout(() => {
                resetForm(formEl)
                get_config_list()
                show_config_box.value = false
              }, 1000)
            })
            .catch((err) => {
              ElMessage.error(err)
            })
        })
        .catch(() => {})
    }
  })
}
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_config_list()
    ElMessage.success('刷新成功！')
  })
  setTimeout(() => {
    get_config_list()
    get_current_config_list()
    get_list()
  }, 100)
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const get_node_list = () => {
  axios
    .request({
      url: serviceApi.taskSetUpNode + '/list',
      method: 'post',
      data: {},
    })
    .then((res) => {
      console.log(res)
      node_list.value = res.data.sort((a, b) => {
        return a.sort - b.sort
      })
      show_node_box.value = true
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const detailList = ref()
const item_info = (e) => {
  axios
    .request({ url: serviceApi.taskWeightConfig + '/' + e.id, method: 'get' })
    .then((res) => {
      console.log(res)
      list.value.forEach((i) => {
        res.data.detailList.some((ii) => {
          if (ii.taskConfigId == i.id) {
            ii.current_weight = i.current_weight
            ii.name = i.name
            ii.code = i.code
          }
          return ii.taskConfigId == i.id
        })
      })
      detailList.value = res.data.detailList
      console.log(list.value, res.data.detailList)
      add_config_form_data.value = {
        id: e.id,
        code: e.code,
        detailList: [],
        enableTime: Number(e.enableTime) as any,
        endTime: Number(e.endTime) as any,
        remark: e.remark,
      }
      show_config_box.value = true
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const submit_task = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      let url = ''
      if (show_config_box.value) {
        url =
          add_form_data.value.id == ''
            ? serviceApi.taskSetUp
            : serviceApi.taskSetUp + '/' + add_form_data.value.id
      } else if (show_node_box.value) {
        url =
          add_form_data.value.id == ''
            ? serviceApi.taskSetUpNode
            : serviceApi.taskSetUpNode + '/' + add_form_data.value.id
      }
      axios
        .request({
          url: url,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            resetForm(formEl)
            show_config_box.value
              ? (get_list(), get_current_config_list())
              : get_node_list()
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const edit_node_list = (e) => {
  console.log(e)
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      name: e.item.name,
      code: '',
      assignWeight: '',
      weight: '',
      sort: e.item.sort,
    }
    show_box.value = true
  } else {
    ElMessageBox.confirm(
      e.item.isEnable ? '确定禁用该子任务' : '确定启用该子任务',
      '',
      {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false,
        type: 'warning',
      }
    )
      .then(() => {
        axios
          .request({
            url:
              serviceApi.taskSetUpNode +
              (e.item.isEnable ? '/disable/' : '/enable/') +
              e.item.id,
            method: 'put',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            e.item.isEnable = !e.item.isEnable
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}
const edit_list = (e) => {
  if (e.type == 1) {
    add_form_data.value = {
      id: e.item.id,
      name: e.item.name,
      code: e.item.code,
      assignWeight: e.item.assignWeight,
      weight: e.item.weight,
      sort: '',
    }
    show_box.value = true
  } else {
    ElMessageBox.confirm(
      e.type == 2 ? '确定禁用该任务？' : '确定启用该任务',
      '',
      {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false,
        type: 'warning',
      }
    )
      .then(() => {
        axios
          .request({
            url:
              serviceApi.taskSetUp +
              (e.type == 2 ? '/disable/' : '/enable/') +
              e.item.id,
            method: 'put',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            if (e.type == 2) {
              e.item.taskWeight = ''
              e.item.isEnable = true
            } else {
              e.item.isEnable = false
            }
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}
const btn_loading = ref(false)
const current_config_detail_list = ref([])
const get_current_config_list = () => {
  axios
    .request({
      url: serviceApi.taskWeightConfig + '/getEnabledTaskWeightConfig',
      method: 'post',
    })
    .then((res) => {
      console.log(res)
      current_config_detail_list.value =
        res.data === null ? [] : res.data.detailList
    })
}
const config_list = ref([])
const current_config_id = ref('')
const total = ref(0)
const get_config_list = () => {
  axios
    .request({
      url: serviceApi.taskWeightConfig + '/taskWeightConfigPage',
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      if (res.data.content.length) {
        current_config_id.value = res.data.content[0].value
      }
      config_list.value = res.data.content
      total.value = Number(res.data.totalElements)
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}

let list_debounce = debounce(200, get_config_list)
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.taskSetUp + '/list',
      method: 'post',
      data: { current: 1, pageSize: 1000 },
    })
    .then((res) => {
      console.log(res)
      if (res.data.length) {
        res.data.forEach((i) => {
          i.weight = ''
          current_config_detail_list.value.some((ii) => {
            if (ii.taskConfigId == i.id) {
              i.current_weight = ii.weight
            }
            return ii.taskConfigId == i.id
          })
        })
      }
      list.value = res.data
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    enableTime: header_list.value[1].value,
    endTine: header_list.value[2].value,
    remark: header_list.value[3].value,
    code: header_list.value[0].value,
  }
  get_config_list()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    code: '',
    assignWeight: '',
    weight: '',
    sort: '',
  }
  show_box.value = false
}
const resetConfigForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_config_form_data.value = {
    id: '',
    code: '',
    detailList: [],
    enableTime: '',
    endTime: '',
    remark: '',
  }
  if (list.value.length) {
    list.value.forEach((i) => {
      i.weight = ''
    })
  }

  show_config_box.value = false
}
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
